package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {
    @Autowired
    ContentServiceClient contentServiceClient;
    @Autowired
    XcChooseCourseMapper xcChooseCourseMapper;
    @Autowired
    XcCourseTablesMapper xcCourseTablesMapper;


    //添加选课课程
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            XueChengPlusException.cast("课程不存在");
        }
        String charge = coursepublish.getCharge();
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        if (charge.equals("201000")) {//免费
            xcChooseCourse = addFreeCoruse(userId,coursepublish);

            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
        }else{//收费
            xcChooseCourse = addChargeCoruse(userId, coursepublish);
        }
        //获取学习资格
        XcCourseTablesDto xcCourseTablesDto = getLearningStatus(userId, courseId);

        XcChooseCourseDto xcChooseCourseDto=new XcChooseCourseDto();
        BeanUtils.copyProperties(xcChooseCourse,xcChooseCourseDto);
        xcChooseCourseDto.setLearnStatus(xcCourseTablesDto.getLearnStatus());

        return xcChooseCourseDto;
    }
    //{"code":"702001","desc":"正常学习"},
    // {"code":"702002","desc":"没有选课或选课后没有支付"},
    // {"code":"702003","desc":"已过期需要申请续期或重新支付"}
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        XcCourseTablesDto xcCourseTablesDto=new XcCourseTablesDto();
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);

        if (xcCourseTables==null){
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }else if (xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now())){
            BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }else {
            BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
            xcCourseTablesDto.setLearnStatus("702001");
            return xcCourseTablesDto;
        }
    }

    //添加免费课程,免费课程加入选课记录表、我的课程表
    public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
        Long courseId=coursepublish.getId();
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        //一个用户选择的一门已选课成功的免费课程
        queryWrapper.eq(XcChooseCourse::getStatus,"701001")
                    .eq(XcChooseCourse::getCourseId,courseId)
                    .eq(XcChooseCourse::getUserId,userId)
                    .eq(XcChooseCourse::getOrderType,"700001");
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
        if (xcChooseCourses.size()>0){
            return xcChooseCourses.get(0);
        }
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700001");//免费课程
        xcChooseCourse.setCoursePrice(0f);
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setValidDays(365);//免费课程默认365天
        xcChooseCourse.setStatus("701001");//选课成功
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert<=0){
            XueChengPlusException.cast("插入选课记录表数据失败");
        }
        return xcChooseCourse;
    }
    //添加到我的课程表
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse){
        String status = xcChooseCourse.getStatus();
        if (!status.equals("701001")){
            XueChengPlusException.cast("选课失败不可添加到我的课程表");
        }
        XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
        if(xcCourseTables!=null){
            return xcCourseTables;
        }
        XcCourseTables xcCourseTablesNew=new XcCourseTables();
        BeanUtils.copyProperties(xcChooseCourse,xcCourseTablesNew);
        xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTablesNew.setUpdateDate(LocalDateTime.now());
        xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType());
        xcCourseTablesMapper.insert(xcCourseTablesNew);
        return xcCourseTablesNew;
    }

    //添加收费课程
    public XcChooseCourse addChargeCoruse(String userId,CoursePublish coursepublish){

        Long courseId=coursepublish.getId();
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcChooseCourse::getStatus,"701002")//待支付
                .eq(XcChooseCourse::getCourseId,courseId)
                .eq(XcChooseCourse::getUserId,userId)
                .eq(XcChooseCourse::getOrderType,"700002");//收费课程
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
        if (xcChooseCourses.size()>0){
            return xcChooseCourses.get(0);
        }
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        Integer validDays = coursepublish.getValidDays();//获取有效期
        xcChooseCourse.setValidDays(validDays);
        xcChooseCourse.setOrderType("700002");//收费课程
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setStatus("701002");//待支付
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(validDays));
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert<=0){
            XueChengPlusException.cast("插入选课记录表数据失败");
        }
        return xcChooseCourse;
    }
    public PageResult<XcCourseTables> mycourestabls(MyCourseTableParams params){
        String userId = params.getUserId();
        int pageNo = params.getPage();
        long pageSize=4;
        Page<XcCourseTables> tablesPage=new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<XcCourseTables> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(XcCourseTables::getUserId,userId);

        Page<XcCourseTables> pageResult=xcCourseTablesMapper.selectPage(tablesPage,queryWrapper);
        List<XcCourseTables> records = pageResult.getRecords();
        long total = pageResult.getTotal();

        PageResult<XcCourseTables> courseTablesResult = new PageResult<>(records, total, pageNo, pageSize);
        return courseTablesResult;
    }

    @Transactional
    @Override
    public boolean saveChooseCourseStauts(String chooseCourseId) {
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);
        if (xcChooseCourse==null){
            log.debug("根据消息id找不到该选课记录");
            return false;
        }
        String status = xcChooseCourse.getStatus();
        if (!status.equals("701002")){
            log.debug("该选课记录订单状态异常");
            return false;
        }
        //待支付更改为支付成功
        xcChooseCourse.setStatus("701001");
        //更新记录表
        xcChooseCourseMapper.updateById(xcChooseCourse);
        //插入我的课程表
        addCourseTabls(xcChooseCourse);
        return true;
    }

    //根据userId和courseId查询我的课程表记录
    public XcCourseTables getXcCourseTables(String userId,Long courseId){
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId).eq(XcCourseTables::getCourseId, courseId));
        return xcCourseTables;

    }
}
